
package unmsm.biometric.view;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import unmsm.fingerprint.HuellaDactilar;
import unmsm.fingerprint.HuellaDactilarGrafica;
import unmsm.fingerprint.PanelHuella;
import FileChooserExtendido.ImageFileView;
import FileChooserExtendido.ImagePreview;
import FileChooserExtendido.ImagenFilter;
//import unmsm.fingerprint.utiles.filechooser.ImageFilter;

public class PanelGraficoDactilar extends javax.swing.JFrame {

  boolean cargaIzquierda = false, cargaDerecha = false;
  // Objetos de las huellas a ser tratados
  private HuellaDactilar objHuella1;
  private HuellaDactilar objHuella2;

  // clase para para binarizar y exqueletizar la imagen, manejan objetos BufferedImage
  private HuellaDactilarGrafica m_fingergfx = new HuellaDactilarGrafica();
  
  //objetos JPanel de c/u de las huellas
  private PanelHuella panelGraficoHuella1 = new PanelHuella();
  private PanelHuella panelGraficoHuella2 = new PanelHuella();

  //Construye un BufferedImage con los parametro predefinidos RGB. este buffer sera pintado en CFingerPrintGraphics
  //BufferedImage.TYPE_INT_RGB: Representa una imagen con los componentes de color RGB de 8 bits empaquetados en píxeles enteros.
  private BufferedImage BufferedImageHuella1;// = new BufferedImage(objHuella1.getImagenAnchoHuella() ,objHuella1.getImagenAltoHuella(),BufferedImage.TYPE_INT_RGB );
  private BufferedImage BufferedImageHuella2; // = new BufferedImage(objHuella2.getImagenAnchoHuella() ,objHuella2.getImagenAltoHuella(),BufferedImage.TYPE_INT_RGB );
  private double arregloDouble1[]; // = new double[objHuella1.getHuellaPlantillaTamanoMax()];
  private double arregloDouble2[]; // = new double[objHuella2.getHuellaPlantillaTamanoMax()];


    public PanelGraficoDactilar() {
        initComponents();
        setImagenVentana();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnPrincipal = new javax.swing.JPanel();
        jbtCargarHuellaDerecha = new javax.swing.JButton();
        jbtCargarHuellaIzquierda = new javax.swing.JButton();
        jpnOpciones = new javax.swing.JPanel();
        jbtCalcular = new javax.swing.JButton();
        jbtLimpiar = new javax.swing.JButton();
        jbtSalir = new javax.swing.JToggleButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Motor Biométrico");
        setBackground(new java.awt.Color(204, 204, 204));

        jpnPrincipal.setBorder(javax.swing.BorderFactory.createTitledBorder("Huellas dactilares"));
        jpnPrincipal.setLayout(null);

        jbtCargarHuellaDerecha.setText("Cargar huella");
        jbtCargarHuellaDerecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCargarHuellaDerechaActionPerformed(evt);
            }
        });
        jpnPrincipal.add(jbtCargarHuellaDerecha);
        jbtCargarHuellaDerecha.setBounds(560, 600, 200, 23);

        jbtCargarHuellaIzquierda.setText("Cargar huella");
        jbtCargarHuellaIzquierda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCargarHuellaIzquierdaActionPerformed(evt);
            }
        });
        jpnPrincipal.add(jbtCargarHuellaIzquierda);
        jbtCargarHuellaIzquierda.setBounds(120, 600, 200, 23);

        jpnOpciones.setBorder(javax.swing.BorderFactory.createTitledBorder("Opciones"));

        jbtCalcular.setText("Comparar");
        jbtCalcular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCalcularActionPerformed(evt);
            }
        });

        jbtLimpiar.setText("Limpiar");

        jbtSalir.setText("Salir");
        jbtSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpnOpcionesLayout = new javax.swing.GroupLayout(jpnOpciones);
        jpnOpciones.setLayout(jpnOpcionesLayout);
        jpnOpcionesLayout.setHorizontalGroup(
            jpnOpcionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnOpcionesLayout.createSequentialGroup()
                .addGap(97, 97, 97)
                .addComponent(jbtCalcular, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(50, 50, 50)
                .addComponent(jbtLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addComponent(jbtSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(245, Short.MAX_VALUE))
        );
        jpnOpcionesLayout.setVerticalGroup(
            jpnOpcionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnOpcionesLayout.createSequentialGroup()
                .addGroup(jpnOpcionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtCalcular)
                    .addComponent(jbtLimpiar)
                    .addComponent(jbtSalir))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jpnPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, 948, Short.MAX_VALUE)
            .addComponent(jpnOpciones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, 645, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jpnOpciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //cargar huella izquierda
    private void jbtCargarHuellaIzquierdaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtCargarHuellaIzquierdaActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.addChoosableFileFilter(new ImagenFilter());
        fc.setFileView(new ImageFileView());
        fc.setAccessory(new ImagePreview(fc));

        int returnVal = fc.showDialog(PanelGraficoDactilar.this, "Buscar");

        if (returnVal == JFileChooser.APPROVE_OPTION) {
             File file = fc.getSelectedFile();
             this.inicializarVariables(1);
             this.cargarImagen(1,file);
             this.procesarHuella(1);
             this.agregarHuellaGrafica(1);
             System.out.println("Se cargo la huella izquierda :"+file.toString());
        } 
        else {
             System.out.println("Se cancelo huella izquierda");
        }
    }//GEN-LAST:event_jbtCargarHuellaIzquierdaActionPerformed

    //cargar huella derecha
    private void jbtCargarHuellaDerechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtCargarHuellaDerechaActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.addChoosableFileFilter(new ImagenFilter());
        fc.setFileView(new ImageFileView());
        fc.setAccessory(new ImagePreview(fc));

        int returnVal = fc.showDialog(PanelGraficoDactilar.this, "Buscar");

        if (returnVal == JFileChooser.APPROVE_OPTION) {
             File file = fc.getSelectedFile();
             this.inicializarVariables(2);
             this.cargarImagen(2,file);
             this.procesarHuella(2);
             this.agregarHuellaGrafica(2);
             System.out.println("Se cargo la huella derecha :"+file.toString());
        }
        else {
             System.out.println("Se cancelo huella derecha");
        }
    }//GEN-LAST:event_jbtCargarHuellaDerechaActionPerformed

    //compracion biometrica
    private void jbtCalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtCalcularActionPerformed
       try{
        
        double var = objHuella1.Match(arregloDouble1 , arregloDouble2,65,false);
        System.out.println("Entra a comparar:"+var);
        JOptionPane.showMessageDialog (null,""+var+"%","Porcentaje de comparación",JOptionPane.PLAIN_MESSAGE);
        comparacionBiometrica();
      }
      catch (Exception ex){
        JOptionPane.showMessageDialog (null,ex.getMessage() ,"Error Message",JOptionPane.PLAIN_MESSAGE);
      }
    }//GEN-LAST:event_jbtCalcularActionPerformed

    private void jbtSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtSalirActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jbtSalirActionPerformed

    //metodos propios
    private void comparacionBiometrica(){
        /*//InputStream in = beanUsuarioRetorno.getHuellaDerecha().getBinaryStream();
            //FileInputStream file = new FileInputStream(new File(beanUsuarioRetorno.getHuellaDerecha().getBinaryStream()));
            //FileInputStream file = (FileInputStream) in;
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println("   ENTRO A PROCESO");
        //BufferedImageHuella1
        ByteArrayOutputStream buffer_img = new ByteArrayOutputStream();
        System.out.println("  PASO 1");
        try {
            ImageIO.write(BufferedImageHuella1, "bmp", buffer_img);
            System.out.println("  PASO 2");

        } catch (IOException ex) {
            System.out.println("   ERROR ImageIO.write");
            ex.printStackTrace();
        }
        byte[] bytes = buffer_img.toByteArray();
        System.out.println("  PASO 3");
        InputStream in = new ByteArrayInputStream(bytes);
        System.out.println("  PASO 4");

        String respuesta = ""; //servicioBiometrico.comparacionBiometrica(in,in);
        System.out.println("::respuesta:: ="+respuesta);*/
    }

    private void procesarHuella(int i){
        if(i==1){
            System.out.println("INGRESA : procesarHuella()");
            //establecer buffer de imagen
            System.out.println(" panelGraficoHuella1.setBufferImagen(BufferedImageHuella1); //establecer buffer de imagen");
            panelGraficoHuella1.setBufferImagen(BufferedImageHuella1);

            //binarizar la huella dactilar
            System.out.println(" BINARIZAR");
            System.out.println("    objHuella1.binarizarHuella(BufferedImageHuella1);");
            objHuella1.binarizarHuella(BufferedImageHuella1) ;

            //obteniendo la plantilla template de la huella dactilar en formato aceptable por NIST
            //la plantilla de la huella se devuelven en un arreglo de double[][]
            arregloDouble1 = objHuella1.getPlantillaHuella();

            //See what skeletinized image looks like
            // Vea lo que la imagen se parece esqueletizada
            BufferedImageHuella1 = objHuella1.getImagenHuellaPintada();
            panelGraficoHuella1.setBufferImagen(BufferedImageHuella1);//BufferedImageHuella1
            //String resultado1 = objHuella1.ConvertFingerPrintTemplateDoubleToString(arregloDouble1);

            panelGraficoHuella1.setBounds(20,20,416,560);
        }
        else{
            //establecer buffer de imagen
            panelGraficoHuella2.setBufferImagen(BufferedImageHuella2);
            //Send image for skeletinization
            objHuella2.binarizarHuella(BufferedImageHuella2) ;
            arregloDouble2=objHuella2.getPlantillaHuella();
            //See what skeletinized image looks like
            BufferedImageHuella2 = objHuella2.getImagenHuellaPintada();
            panelGraficoHuella2.setBufferImagen(BufferedImageHuella2);

            panelGraficoHuella2.setBounds(460,20,416,560);
        }
    }
    
    private void agregarHuellaGrafica( int i){
        if(i==1 && !cargaIzquierda){
             jpnPrincipal.add(panelGraficoHuella1);
             cargaIzquierda = true;
        }
        if(i==2 && !cargaDerecha){
             jpnPrincipal.add(panelGraficoHuella2);
             cargaDerecha = true;
        }
        jpnPrincipal.repaint();
    }

    private void cargarImagen(int i, File file){
       try {
           System.out.println("INGRESA : cargarImagen()");
           if(i==1){
               System.out.println(" BufferedImageHuella1 = ImageIO.read( file:"+ImageIO.read(file)+")");
               BufferedImageHuella1 = ImageIO.read(file);
               System.out.println(" BufferedImageHuella1 = "+BufferedImageHuella1+"");
           }
           else{
               BufferedImageHuella2 = ImageIO.read(file);//ImageIO.read(new File(new java.io.File("").getAbsolutePath() + "\\src\\unmsm\\fingerprint\\app\\huellaFinal.bmp")) ;
           }
        } catch (IOException ex) {
            Logger.getLogger(PanelGraficoDactilar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void inicializarVariables(int i){
        System.out.println("INGRESA : inicializarVariables()");
        if(i == 1){
            objHuella1 = new HuellaDactilar();
            //panelGraficoHuella1 = new PanelHuella();
            arregloDouble1 = new double[objHuella1.getHuellaPlantillaTamanoMax()];
            System.out.println(" arregloDouble1 = double["+arregloDouble1.length+"]");
            /*for(int a = 0; a<arregloDouble1.length; a++){
                System.out.println(""+a+": "+arregloDouble1[a]);
            }*/ 
            System.out.println(" BufferedImageHuella1 = BufferedImage(ancho:"+objHuella1.getImagenAnchoHuella()+")");
            System.out.println(" BufferedImageHuella1 = BufferedImage(alto:"+objHuella1.getImagenAltoHuella()+")");
            System.out.println(" BufferedImageHuella1 = BufferedImage(BufferedImage.TYPE_INT_RGB:"+BufferedImage.TYPE_INT_RGB+")");
            BufferedImageHuella1 = new BufferedImage(objHuella1.getImagenAnchoHuella() ,objHuella1.getImagenAltoHuella(),BufferedImage.TYPE_INT_RGB );   
        }
        else{
            objHuella2 = new HuellaDactilar();
            //panelGraficoHuella2 = new PanelHuella();
            arregloDouble2 = new double[objHuella2.getHuellaPlantillaTamanoMax()];
            BufferedImageHuella2 = new BufferedImage(objHuella2.getImagenAnchoHuella() ,objHuella2.getImagenAltoHuella(),BufferedImage.TYPE_INT_RGB );
        }
    }

    
    //cargar imagen de la ventanita
    private void setImagenVentana(){
	BufferedImage image = null;
	try{
	    image = ImageIO.read(new File(new java.io.File("").getAbsolutePath()+"\\src\\unmsm\\biometric\\view\\logo.jpg"));
	} catch (IOException e) {
	    e.printStackTrace();
	}
        this.setIconImage(image);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PanelGraficoDactilar().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jbtCalcular;
    private javax.swing.JButton jbtCargarHuellaDerecha;
    private javax.swing.JButton jbtCargarHuellaIzquierda;
    private javax.swing.JButton jbtLimpiar;
    private javax.swing.JToggleButton jbtSalir;
    private javax.swing.JPanel jpnOpciones;
    private javax.swing.JPanel jpnPrincipal;
    // End of variables declaration//GEN-END:variables

}
